<template>
  <view class="home-top-nav">
    <van-nav-bar
      :title="title"
      :left-arrow="false"
      :border="false"
      placeholder
      custom-style="color: '#fff';background:none;font-size:36rpx;"
      fixed
    />
    <view class="search-page" v-if="isSearch" @click="goPage">
      <view class="search-box">
        <van-icon name="search" size="20" />
        <text>{{ searchVal }}</text>
      </view>
      <view slot="action" class="search-btn">搜索</view>
    </view>
  </view>
</template>

<script>
import { reactive, toRefs, onMounted } from 'vue'
export default {
  name: 'title',
  props: {
    title: {
      type: String,
      default: '',
    },
    isSearch: {
      type: Boolean,
      default: true,
    },
    searchVal: {
      type: String,
      default: '请输入商品名',
    },
  },
  setup(props, { emit }) {
    const state = reactive({
      height: 26,
      statusBarHeight: 0,
      navBarHeight: 52,
      searchVal: props.searchVal,
    })
    const getHeight = () => {
      // 判断获取微信小程序胶囊API是否可用
      if (uni.canIUse('getMenuButtonBoundingClientRect')) {
        // 获取状态栏高度(电量时间通知等信息-单位px)
        let sysInfo = uni.getSystemInfoSync()
        state.statusBarHeight = sysInfo.statusBarHeight
        let navBarHeight = 0

        // 获取微信小程序胶囊布局位置信息
        let rect = uni.getMenuButtonBoundingClientRect()
        // (胶囊上部高度-状态栏高度)*2 + 胶囊高度 = 导航栏高度（不包含状态栏）
        //以此保证胶囊位于中间位置，多机型适配

        navBarHeight = (rect.top - sysInfo.statusBarHeight) * 2 + rect.height
        state.navBarHeight = navBarHeight
        // 状态栏高度 + 导航栏高度 = 自定义导航栏高度总和
        state.height = sysInfo.statusBarHeight + navBarHeight

        emit('getHeadHeight', state.height)
      } else {
        uni.showToast({
          title: '您的微信版本过低，界面可能会显示不正常',
          icon: 'none',
          duration: 4000,
        })
      }
    }
    const goPage = () => {
      uni.navigateTo({
        url: `/subpackage-goods/search/index`,
      })
    }
    onMounted(() => {
      // #ifdef MP-WEIXIN
      getHeight()
      // #endif
    })
    return {
      ...toRefs(state),
      getHeight,
      goPage,
    }
  },
}
</script>

<style lang="scss" scoped>
.home-top-nav {
  .title-text {
    font-weight: 500;
    text-align: center;
    height: 52rpx;
    font-size: 36rpx;
  }
}
.search-page {
  position: relative;
  padding: 10rpx 24rpx;
  height: 52rpx;
  margin: 0 24rpx 24rpx;
  background: #ffffff;
  border-radius: 40rpx;
  border: 2rpx solid #3775f2;
  font-size: 24rpx;
  color: #7f8798;
  line-height: 52rpx;

  .search-box {
    display: flex;
    align-items: center;
  }
  .search-btn {
    display: block;
    position: absolute;
    right: 10rpx;
    top: 8rpx;
    width: 112rpx;
    height: 56rpx;
    line-height: 56rpx;
    text-align: center;
    font-size: 24rpx;
    color: #fff;
    z-index: 9;
    background: linear-gradient(90deg, #38acff 0%, #387bff 100%);
    border-radius: 28rpx;
  }
}
</style>
